package cn.rsa.aiwangren.advice;

import cn.rsa.aiwangren.annotation.Encrypt;
import cn.rsa.aiwangren.config.SecretKeyConfig;
import cn.rsa.aiwangren.util.Base64Util;
import cn.rsa.aiwangren.util.RSAUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Objects;


/**
 * 对响应进行处理
 *
 * @author xiangtianlei
 * @date 2024/04/09
 */
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private static final ThreadLocal<Boolean> encryptLocal = new ThreadLocal<>();
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private boolean encrypt;
    private String publicKey;
    @Autowired
    private SecretKeyConfig secretKeyConfig;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        encrypt = false;
        if (Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(Encrypt.class) && secretKeyConfig.isOpen()) {
            encrypt = true;
            Method method = returnType.getMethod();
            String channel = method.getAnnotation(Encrypt.class).value();
            try {
                publicKey = secretKeyConfig.getKeyPair(channel).getPublicKey();
            } catch (Exception e) {
                log.error("\nThe: {} channel may not have found the corresponding public key", channel);
            }
        }
        return encrypt;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Boolean status = encryptLocal.get();
        if (null != status && !status) {
            encryptLocal.remove();
            return body;
        }
        if (encrypt) {
            try {
                String content = JSONObject.toJSONString(body).replace("\\", "");
                if (!StringUtils.hasText(this.publicKey)) {
                    throw new NullPointerException("Please configure rsa.encrypt.private key parameter!");
                }
                byte[] data = content.getBytes();
                byte[] encodedData = RSAUtil.encrypt(data, this.publicKey, secretKeyConfig.getMAX_ENCRYPT_BLOCK());
                String result = Base64Util.encode(encodedData);
                if (secretKeyConfig.isShowLog()) {
                    log.info("\nPre-encrypted data：{}，After encryption：{}", content, result);
                }
                return result;
            } catch (Exception e) {
                log.error("\nEncrypted data exception", e);
            }
        }
        return body;
    }
}
